package com.qf.smsplatform.strategy.executor;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.enums.SmsEnum;
import com.qf.smsplatform.common.exception.SmsException;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.client.CacheClient;
import com.qf.smsplatform.strategy.strategy.Strategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 策略链的执行者，指定策略链的执行顺序
 * @author zjw
 */
@Component
@Slf4j
public class StrategyExecutor {

    /**
     * 需要拿到所有的策略对象
     */
    @Autowired
    private Map<String, Strategy> strategyMap;
    // router
    // routerStrategyImpl

    /**
     * 调用缓存模块的feign接口
     */
    @Autowired
    private CacheClient cacheClient;



    public void execute(StandardSubmit submit){
        //1. 从其他位置获取到策略对象的执行顺序
        String filters = cacheClient.hget(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(),"filters");

        //2. 根据执行顺序依次执行每一个策略的execute方法，并根据返回结果，判断是否需要执行下一个
        if(StringUtils.isEmpty(filters)) {
            log.info("【策略模块-执行策略链】 无法查询到当前客户的策略链执行顺序！ filters = {}",filters);
            throw new SmsException(SmsEnum.ERROR);
        }
        String[] filterArray = filters.split(",");
        for (String filter : filterArray) {
            // phase,black,dirtyWord,limitFiveMinutes,limitOneHour,limitOneDay,fee,router
            Strategy strategy = strategyMap.get(filter);
            if(strategy != null){
                boolean flag = strategy.execute(submit);
                if(!flag){
                    // 凉凉
                    return;
                }
            }
        }
    }
}
